package www.wen.com.common.lib.util

import www.wen.com.common.R
import www.wen.com.common.lib.app.BaseApplication
import www.wen.com.common.lib.extension.getString
import java.util.regex.Pattern
import www.wen.com.common.lib.data.entities.builtIn.Result

/**
 * @author WEN
 * @Description:
 * @date 2021/1/28 13:41
 */
object StringUtil {

    /**
     * 简单判断字符串是否为邮箱
     */
    fun String.checkIsEmail(error: ((String) -> Unit)? = null): Boolean {
        if (this.isBlank()) {
            error?.invoke(BaseApplication.CONTEXT.getString(R.string.pleaseInputYourEmail))
            return false
        } else if (this.trim().contains(" ") || !this.contains("@") || this.endsWith("@") || this.startsWith("@")) {
            error?.invoke(BaseApplication.CONTEXT.getString(R.string.eMailFormatIsIncorrect))
            return false
        }
        return true
    }

    /**
     * 判断字符串是否为密码
     */
    fun String.checkIsPassword(error: ((String) -> Unit)? = null): Boolean {
        if (this.isBlank()) {
            error?.invoke(BaseApplication.CONTEXT.getString(R.string.pleaseEnterPassword))
            return false
        } else if (this.contains(" ")) {
            error?.invoke(BaseApplication.CONTEXT.getString(R.string.passwordCannotUseSpaces))
            return false
        }
        return true
    }

    fun checkVerificationCode(s: String, error: ((String) -> Unit)? = null): Boolean {
        return if (s.isBlank()) {
            error?.invoke(BaseApplication.CONTEXT.getString(R.string.pleaseEnterVerificationCode))
            false
        } else {
            val mainRegex = "^[+]{0,1}(\\d+)\$"
            val p = Pattern.compile(mainRegex)
            val m = p.matcher(s)
            val isCode = m.matches()
            if (!isCode) {
                error?.invoke(BaseApplication.CONTEXT.getString(R.string.verificationCodeError))
            }
            isCode
        }
    }

    fun checkIsName(s: String, error: ((String) -> Unit)? = null): Boolean {
        return if (s.isBlank()) {
            error?.invoke(BaseApplication.CONTEXT.getString(R.string.please_enter_the_name))
            false
        } else {
            true
        }
    }

    fun getErrorMsg(result: Result.Error): String {
        return if (result.exception.message != null && result.exception.message != getString(R.string.networkAnomaly)) {
            return when (result.exception.message) {
                "账号已经被注册" -> {
                    getString(R.string.accountHasBeenRegistered)
                }
                "账号密码错误" -> {
                    getString(R.string.incorrectEmailOrPassword)
                }
                "该邮箱已被注册" -> {
                    getString(R.string.the_mailbox_has_been_registered)
                }
                else -> {
                    getString(R.string.networkAnomaly)
                }
            }
        } else getString(R.string.networkAnomaly)
    }

}